import { BasePlugin } from '../plugin-system/base-plugin.js'
import { createLogger } from '../utils/logger.js'

const logger = createLogger('LSPClient')
import completionsData from '../completions.json'

/**
 * LSP客户端插件
 * 提供语言服务器协议客户端功能
 */
export class LSPClientPlugin extends BasePlugin {
    constructor(editor, options = {}) {
        super(editor, {
            // 默认配置
            serverUrl: null,
            language: 'javascript',
            enableCompletion: true,
            enableDiagnostics: true,
            enableHover: true,
            reconnectAttempts: 3,
            reconnectDelay: 1000,
            ...options
        })
        
        this.completionsData = null
        this.isConnected = false
        this.reconnectCount = 0
    }
    
    initialize() {
        // 初始化LSP客户端数据
        this.completionsData = completionsData
        
        // 模拟连接状态
        this.isConnected = true
    }
    
    onEnable() {
        if (!this.completionsData) {
            this.initialize()
        }
        
        // 尝试连接到语言服务器
        this.connect()
        
        this.emit('lsp:enabled')
    }
    
    onDisable() {
        // 断开连接
        this.disconnect()
        
        this.emit('lsp:disabled')
    }
    
    onDestroy() {
        this.disconnect()
        this.completionsData = null
    }
    
    /**
     * 连接到语言服务器
     */
    async connect() {
        try {
            if (this.options.serverUrl) {
                // 这里可以实现真正的WebSocket连接
                // const socket = new WebSocket(this.options.serverUrl)
                // await this.setupConnection(socket)
                logger.success(`连接到LSP服务器: ${this.options.serverUrl}`)
            }
            
            this.isConnected = true
            this.reconnectCount = 0
            this.emit('lsp:connected', { serverUrl: this.options.serverUrl })
            
        } catch (error) {
            logger.error('LSP连接失败:', error)
            this.isConnected = false
            this.emit('lsp:connectionError', { error })
            
            // 尝试重连
            if (this.reconnectCount < this.options.reconnectAttempts) {
                this.scheduleReconnect()
            }
        }
    }
    
    /**
     * 断开连接
     */
    disconnect() {
        this.isConnected = false
        // 这里可以关闭WebSocket连接
        this.emit('lsp:disconnected')
    }
    
    /**
     * 安排重连
     */
    scheduleReconnect() {
        this.reconnectCount++
        setTimeout(() => {
            logger.info(`尝试重连LSP服务器 (${this.reconnectCount}/${this.options.reconnectAttempts})`)
            this.connect()
        }, this.options.reconnectDelay)
    }
    
    /**
     * 生成代码补全
     */
    generateCompletions(text, line, character) {
        if (!this.isConnected || !this.completionsData) {
            return []
        }
        
        try {
            const completions = this.getCompletions(text, line, character)
            this.emit('lsp:completions', { completions, line, character })
            return completions
        } catch (error) {
            this.emit('lsp:error', { action: 'completion', error })
            return []
        }
    }
    
    /**
     * 获取悬停信息
     */
    getHoverInfo(text, line, character) {
        if (!this.isConnected || !this.completionsData || !this.options.enableHover) {
            return null
        }
        
        try {
            // 这里可以实现真正的悬停信息获取
            const hoverInfo = {
                contents: '这是悬停信息',
                range: { start: character, end: character + 5 }
            }
            
            this.emit('lsp:hover', { hoverInfo, line, character })
            return hoverInfo
        } catch (error) {
            this.emit('lsp:error', { action: 'hover', error })
            return null
        }
    }
    
    /**
     * 获取诊断信息
     */
    getDiagnostics(text) {
        if (!this.isConnected || !this.completionsData || !this.options.enableDiagnostics) {
            return []
        }
        
        try {
            // 这里可以实现真正的诊断信息获取
            const diagnostics = []
            
            this.emit('lsp:diagnostics', { diagnostics })
            return diagnostics
        } catch (error) {
            this.emit('lsp:error', { action: 'diagnostics', error })
            return []
        }
    }
    
    /**
     * 查找定义
     */
    findDefinition(text, line, character) {
        if (!this.isConnected || !this.completionsData) {
            return null
        }
        
        try {
            // 这里可以实现真正的定义查找
            const definition = {
                uri: 'file://example.js',
                range: {
                    start: { line: 0, character: 0 },
                    end: { line: 0, character: 10 }
                }
            }
            
            this.emit('lsp:definition', { definition, line, character })
            return definition
        } catch (error) {
            this.emit('lsp:error', { action: 'definition', error })
            return null
        }
    }
    
    /**
     * 查找引用
     */
    findReferences(text, line, character) {
        if (!this.isConnected || !this.completionsData) {
            return []
        }
        
        try {
            // 这里可以实现真正的引用查找
            const references = []
            
            this.emit('lsp:references', { references, line, character })
            return references
        } catch (error) {
            this.emit('lsp:error', { action: 'references', error })
            return []
        }
    }
    
    /**
     * 格式化代码
     */
    formatDocument(text) {
        if (!this.isConnected || !this.completionsData) {
            return text
        }
        
        try {
            // 这里可以实现真正的代码格式化
            const formattedText = text // 简单返回原文本
            
            this.emit('lsp:format', { originalText: text, formattedText })
            return formattedText
        } catch (error) {
            this.emit('lsp:error', { action: 'format', error })
            return text
        }
    }
    
    /**
     * 重命名符号
     */
    rename(text, line, character, newName) {
        if (!this.isConnected || !this.completionsData) {
            return null
        }
        
        try {
            // 这里可以实现真正的重命名功能
            const workspaceEdit = {
                changes: {
                    'file://example.js': [{
                        range: {
                            start: { line, character },
                            end: { line, character: character + 5 }
                        },
                        newText: newName
                    }]
                }
            }
            
            this.emit('lsp:rename', { workspaceEdit, line, character, newName })
            return workspaceEdit
        } catch (error) {
            this.emit('lsp:error', { action: 'rename', error })
            return null
        }
    }
    
    /**
     * 获取语言
     */
    getLanguage() {
        return this.completionsData ? this.completionsData.language : this.options.language
    }
    
    /**
     * 设置语言
     */
    setLanguage(language) {
        this.options.language = language
        this.emit('lsp:languageChanged', { language })
    }
    
    /**
     * 检查连接状态
     */
    isLSPConnected() {
        return this.isConnected
    }
    
    /**
     * 获取连接状态信息
     */
    getConnectionInfo() {
        return {
            connected: this.isConnected,
            serverUrl: this.options.serverUrl,
            language: this.getLanguage(),
            reconnectCount: this.reconnectCount,
            options: {
                enableCompletion: this.options.enableCompletion,
                enableDiagnostics: this.options.enableDiagnostics,
                enableHover: this.options.enableHover
            }
        }
    }
    
    /**
     * 发射事件的便捷方法
     */
    emit(event, data) {
        this.editor.emit(event, data)
    }
    
    /**
     * 获取代码补全建议
     */
    getCompletions(text, line, character) {
        const completions = []
        const context = this.getContext(text, line, character)
        
        // 查找匹配的上下文（按照触发器长度降序排列，优先匹配最具体的）
        const sortedContexts = [...this.completionsData.contexts].sort((a, b) => {
            const maxTriggerLengthA = Math.max(...a.triggers.map(t => t.length))
            const maxTriggerLengthB = Math.max(...b.triggers.map(t => t.length))
            return maxTriggerLengthB - maxTriggerLengthA
        })
        
        for (const ctx of sortedContexts) {
            for (const trigger of ctx.triggers) {
                if (context.endsWith(trigger)) {
                    completions.push(...ctx.items)
                    return completions
                }
            }
        }
        
        // 默认补全
        completions.push(...this.completionsData.default)
        return completions
    }
    
    /**
     * 获取上下文
     */
    getContext(text, line, character) {
        const lines = text.split('\n')
        const currentLine = lines[line] || ''
        const textBeforeCursor = currentLine.substring(0, character)
        
        // 从光标位置向前查找最近的上下文（包括点号和单词）
        let context = ''
        let foundValidContext = false
        
        // 从光标位置向前查找，直到遇到空格或其他分隔符
        for (let i = character - 1; i >= 0; i--) {
            const char = textBeforeCursor[i]
            
            if (/[a-zA-Z0-9_.]/.test(char)) {
                context = char + context
                foundValidContext = true
            } else if (/\s/.test(char)) {
                // 遇到空格就停止
                break
            } else {
                // 遇到其他字符也停止
                break
            }
        }
        
        return foundValidContext ? context : ''
    }
}